/*
 * Copyright 2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.oschina.durcframework.easymybatis.ext.code.generator;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Transient;

import net.oschina.durcframework.easymybatis.ext.code.util.ReflectionUtils;

/**
 * 表信息查询
 */
public class ColumnSelector {

	
	
	
	private String getColumnType(Field field) {
		return field.getType().getSimpleName();
	}
	
	private String getColumnName(Field field) {
		String columnName = "";
		Column column = field.getAnnotation(Column.class);
		if(column == null) {
			columnName = field.getName();
		}else {
			columnName = column.name();
		}
		
		return columnName;
	}
	
	private boolean isPK(Field field) {
		return field.getAnnotation(Id.class) != null;
	}
	
	private boolean isIdentity(Field field) {
		GeneratedValue gv = field.getAnnotation(GeneratedValue.class);
		return gv != null && gv.strategy() == GenerationType.IDENTITY;
	}
	
	public List<ColumnDefinition> getColumnDefinitions(Class<?> entityClass) {
		List<ColumnDefinition> columnDefinitionList = new ArrayList<ColumnDefinition>();
		// 构建columnDefinition
		
		List<Field> fields = ReflectionUtils.getDeclaredFields(entityClass);
		
		ColumnDefinition cd = null;
		for (Field field : fields) {
			cd = buildColumnDefinition(field);
			if(cd != null) {
				columnDefinitionList.add(cd);
			}
		}
					
		return columnDefinitionList;
	}
	
	/**
	 * 构建列信息
	 * @param field 字段信息
	 * @return
	 */
	protected ColumnDefinition buildColumnDefinition(Field field) {
		ColumnDefinition columnDefinition = new ColumnDefinition();
		
		Transient transientAnno = field.getAnnotation(Transient.class);
		
		columnDefinition.setTransient(transientAnno != null);
		
		String columnName = this.getColumnName(field);
		String columnType = this.getColumnType(field);
		
		columnDefinition.setJavaFieldName(field.getName());
		columnDefinition.setColumnName(columnName);
		columnDefinition.setIsPk(this.isPK(field));
		columnDefinition.setIsIdentity(isIdentity(field));
		columnDefinition.setType(columnType);
		
		return columnDefinition;
	}
	
}
